from flask import g, Blueprint, request, jsonify, render_template, session, redirect
from models import Classes, Teacher, Student, SignIn
from exts import db, get_time, to_json_all
from flask_login import login_required
from common import Result

bp = Blueprint("sign_in", __name__, url_prefix="/sign_in")


# todo before_request
@bp.before_request
# @login_required
def before_request():
    pass


# todo add_sign_in
@bp.route("/add_sign_in", methods=["POST"])
def add_sign_in():
    data = eval(request.values.get("data"))
    id_classes = request.values.get("id_classes")
    for i in data:
        s = SignIn(
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0,
            student=db.session.query(Student).get(i["id"]),
            classes=db.session.query(Classes).get(id_classes)
        )
        db.session.add(s)

    db.session.commit()

    result = Result()
    return result.success(msg="签到成功")


# todo delete_sign_in
@bp.route("/delete_sign_in", methods=["POST"])
def delete_sign_in():
    id_sign_in = request.values.get("id_sign_in")
    result = Result()

    try:
        db.session.query(SignIn).filter(SignIn.id == id_sign_in).delete()
        db.session.commit()
    except:
        return result.error(msg="error")

    return result.success(msg="success")


# todo query_sign_in_by_student
@bp.route("/query_sign_in_by_student", methods=["GET"])
def query_sign_in_by_student():
    id_student = int(request.values.get("id_student"))
    data = {
        "code": 0,
        "msg": "",
        "count": 0,
        'data': []
    }

    sign_in = db.session.query(SignIn).filter(SignIn.id_student == id_student).all()
    for i in sign_in:
        data["data"].append({
            "id": i.id,
            "name": i.student.name,
            "create_time": i.create_time
        })
        data["count"] += 1

    # print(data)
    return jsonify(data)


# todo query_sign_in_by_classes
@bp.route("/query_sign_in_by_classes", methods=["GET"])
def query_sign_in_by_classes():
    page = int(request.values.get("page"))
    limit = int(request.values.get("limit"))
    id_classes = int(request.values.get("id_classes"))
    # result = Result()
    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(SignIn).filter(SignIn.id_classes == id_classes).all()),
        "data": []
    }

    for i in db.session.query(SignIn).filter(SignIn.id_classes == id_classes).order_by(SignIn.create_time.desc()).paginate(page=page, per_page=limit).items:
        data["data"].append({
            "name": i.student.name,
            "create_time": i.create_time
        })

    return jsonify(data)
